package com.sabm.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.sabm.model.Account;
import com.sabm.model.Address;
import com.sabm.model.Contact;
import com.sabm.model.Email;
import com.sabm.model.Phone;

@Repository
public class ContactDAOImpl implements ContactDAO {
	@Autowired
    private SessionFactory sessionFactory;
	@Autowired
	private AddressDAOImpl addressDAO;
	@Autowired
	private EmailDAOImpl emailDAO;
	@Autowired
	private PhoneDAOImpl phoneDAO;
	
	public void saveOrUpdateAddress(Address address){
		if(address.isRemove()){
			addressDAO.delete(address);
		}else{
			addressDAO.saveOrUpdate(address);
		}
	}
	public void saveOrUpdateEmail(Email email){
		if(email.isRemove()){
			emailDAO.delete(email);
		}else{
			emailDAO.saveOrUpdate(email);
		}
	}
	public void saveOrUpdatePhone(Phone phone){
		if(phone.isRemove()){
			phoneDAO.delete(phone);
		}else{
			phoneDAO.saveOrUpdate(phone);
		}
	}
	//
	public void save(Contact contact){
		sessionFactory.getCurrentSession().save(contact);
	}
	//
	public void delete(Contact contact){
		sessionFactory.getCurrentSession().delete(contact);
	}
	//
	public void update(Contact contact){
		sessionFactory.getCurrentSession().update(contact);
	}
	//
	public List<Contact> getListContacts(int idAccount){
		Query query = sessionFactory.getCurrentSession().createQuery("from Contact where idAccount = :idAccount ORDER BY firstName ASC");
		query.setParameter("idAccount", idAccount);
		List<Contact> list = query.list();
		return list;
	}
	//
	public List<Contact> getListContacts(int idAccount, int start, int length){
		Query query = sessionFactory.getCurrentSession().createQuery("from Contact where idAccount = :idAccount ORDER BY firstName ASC");
		query.setParameter("idAccount", idAccount);
		query.setFirstResult(start);
		query.setMaxResults(length);
		List<Contact> list = query.list();
		return list;
	}
	//
	public int getTotalContacts(int idAccount){
		Query query = sessionFactory.getCurrentSession().createQuery("select count(*) from Contact where idAccount = :idAccount");
		query.setParameter("idAccount", idAccount);
		int total = ((Long)query.uniqueResult()).intValue();
		return total;
	}
	//
	public Contact getContactById(int idContact){
		Query query = sessionFactory.getCurrentSession().createQuery("from Contact where idContact = :idContact ");
		query.setParameter("idContact", idContact);
		List<Contact> list = query.list();
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}

}
